package com.hp.fremarker.web.handler;

import com.hp.fremarker.beans.BeanFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author dongxing
 **/
public class MappingHandler {


    private String uri;
    private Method method;
    private Class<?> controller;
    private String[] args;

    public MappingHandler(String uri, Method method, Class<?> controller, String[] args) {
        this.uri = uri;
        this.method = method;
        this.controller = controller;
        this.args = args;
    }

    public boolean handler(ServletRequest req, ServletResponse res) throws IllegalAccessException, InstantiationException, InvocationTargetException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        String requestURI = request.getRequestURI();

        // 判断请求的路径是否相等
        if (!uri.equals(requestURI)) {
            return false;
        }
        // 取出请求的参数
        Object[] paramerties = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            paramerties[i] = request.getParameter(args[i]);
        }
        // 执行方法
        Object ctl = BeanFactory.getBean(controller);
        Object response = method.invoke(ctl, paramerties);
        res.getWriter().println(response.toString());
        return true;

    }
}
